import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15

Item {
    id: root
    
    property alias bubbleWidget: bubble
    property int animationDuration: 300
    property bool isAnimating: false
    
    signal aboutToShow()
    signal aboutToClose()
    signal animationStarted()
    signal animationFinished()
    signal animationStopped()
    
    visible: false
    width: 0
    height: 0
    opacity: 1.0  // 初始透明度
    z: 10000  // 确保显示在最上层，使用更大的值
    clip: true
    
    // 气泡组件
    BubbleWidget {
        id: bubble
        anchors.fill: parent
        
        Component.onCompleted: {
            // 组件创建完成，但不立即绘制
        }
    }
    
    onVisibleChanged: {
        if (visible && bubble && bubble.canvas && root.width > 0 && root.height > 0) {
            Qt.callLater(function() {
                if (bubble && bubble.canvas) {
                    bubble.canvas.requestPaint()
                }
            })
        }
    }
    
    // 显示动画
    PropertyAnimation {
        id: showAnimation
        target: root
        property: "opacity"
        from: 0.0
        to: 1.0
        duration: root.animationDuration
        easing.type: Easing.OutCubic
        
        onStarted: {
            root.isAnimating = true
            root.animationStarted()
        }
        
        onFinished: {
            root.isAnimating = false
            root.animationFinished()
        }
    }
    
    // 隐藏动画
    PropertyAnimation {
        id: hideAnimation
        target: root
        property: "opacity"
        from: 1.0
        to: 0.0
        duration: root.animationDuration
        easing.type: Easing.InCubic
        
        onStarted: {
            root.isAnimating = true
            root.animationStarted()
        }
        
        onFinished: {
            root.isAnimating = false
            root.visible = false
            root.animationFinished()
            root.aboutToClose()
        }
    }
    
    // 显示在指定位置
    function showAt(pos, direction) {
        if (!bubble || !pos) {
            console.log("BubbleWrapper.showAt: bubble or pos is null")
            return
        }
        
        try {
            bubble.direction = direction !== undefined ? direction : bubble.directionBottom
            
            // 先更新气泡尺寸
            var optimalSize = bubble.calculateOptimalSize()
            if (!optimalSize || optimalSize.width <= 0 || optimalSize.height <= 0) {
                optimalSize = Qt.size(200, 100)  // 默认大小
            }
            
            root.width = optimalSize.width + 20  // 添加边距
            root.height = optimalSize.height + 20
            
            console.log("BubbleWrapper.showAt: size=" + root.width + "x" + root.height + ", pos=(" + pos.x + "," + pos.y + "), direction=" + direction)
            
            // 等待一帧确保尺寸更新
            Qt.callLater(function() {
                try {
                    var triW = (bubble.triangleSize && bubble.triangleSize.width) ? bubble.triangleSize.width : 10
                    var triH = (bubble.triangleSize && bubble.triangleSize.height) ? bubble.triangleSize.height : 10
                    
                    // Item 使用 x 和 y 属性定位（相对于 parent，即 ApplicationWindow）
                    var adjustedX = pos.x || 0
                    var adjustedY = pos.y || 0
                    
                    // 根据方向调整位置
                    switch (direction) {
                    case bubble.directionTop:
                        adjustedY -= (root.height + triH)
                        adjustedX -= root.width / 2
                        break
                    case bubble.directionBottom:
                        adjustedY += triH
                        adjustedX -= root.width / 2
                        break
                    case bubble.directionLeft:
                        adjustedX -= (root.width + triW)
                        adjustedY -= root.height / 2
                        break
                    case bubble.directionRight:
                        adjustedX += triW
                        adjustedY -= root.height / 2
                        break
                    }
                    
                    // 确保在屏幕内
                    var screenWidth = Screen.width || 800
                    var screenHeight = Screen.height || 600
                    adjustedX = Math.max(0, Math.min(adjustedX, screenWidth - root.width))
                    adjustedY = Math.max(0, Math.min(adjustedY, screenHeight - root.height))
                    
                    // 设置 Item 的位置
                    root.x = adjustedX
                    root.y = adjustedY
                    
                    console.log("BubbleWrapper.showAt: final position=(" + root.x + "," + root.y + "), visible=" + root.visible)
                    
                    // 确保Canvas绘制
                    if (bubble && bubble.canvas) {
                        Qt.callLater(function() {
                            if (bubble && bubble.canvas && root.width > 0 && root.height > 0) {
                                console.log("BubbleWrapper.showAt: requesting paint, canvas size=" + bubble.canvas.width + "x" + bubble.canvas.height)
                                bubble.canvas.requestPaint()
                            }
                        })
                    }
                    
                    showAnimated()
                } catch (e) {
                    console.log("BubbleWrapper.showAt error:", e)
                }
            })
        } catch (e) {
            console.log("BubbleWrapper.showAt outer error:", e)
        }
    }
    
    // 显示在控件附近
    function showNearItem(item, direction, margin) {
        if (!item) return
        
        // 获取item在ApplicationWindow中的位置
        var itemPos = item.mapToItem(root.parent, 0, 0)
        if (!itemPos || itemPos.x === undefined) {
            // 如果mapToItem失败，尝试直接获取位置
            itemPos = Qt.point(item.x, item.y)
        }
        
        var targetPos
        
        switch (direction) {
        case bubble.directionTop:
            targetPos = Qt.point(itemPos.x + item.width / 2, itemPos.y - margin)
            break
        case bubble.directionBottom:
            targetPos = Qt.point(itemPos.x + item.width / 2, itemPos.y + item.height + margin)
            break
        case bubble.directionLeft:
            targetPos = Qt.point(itemPos.x - margin, itemPos.y + item.height / 2)
            break
        case bubble.directionRight:
            targetPos = Qt.point(itemPos.x + item.width + margin, itemPos.y + item.height / 2)
            break
        }
        
        showAt(targetPos, direction)
    }
    
    // 动画显示
    function showAnimated() {
        if (!bubble) {
            console.log("BubbleWrapper.showAnimated: bubble is null")
            return
        }
        
        console.log("BubbleWrapper.showAnimated: width=" + root.width + ", height=" + root.height + ", visible=" + root.visible)
        
        // 先设置可见和尺寸
        root.visible = true
        root.opacity = animationDuration <= 0 ? 1.0 : 0.0
        
        root.aboutToShow()
        
        // 确保Canvas绘制
        Qt.callLater(function() {
            if (bubble && bubble.canvas && root.width > 0 && root.height > 0) {
                console.log("BubbleWrapper.showAnimated: requesting paint")
                bubble.canvas.requestPaint()
            } else {
                console.log("BubbleWrapper.showAnimated: cannot paint, bubble=" + bubble + ", canvas=" + (bubble ? bubble.canvas : null) + ", width=" + root.width + ", height=" + root.height)
            }
        })
        
        if (animationDuration <= 0) {
            return
        }
        
        if (isAnimating) {
            stopAnimation()
        }
        
        showAnimation.start()
    }
    
    // 动画隐藏
    function hideAnimated() {
        if (animationDuration <= 0) {
            root.visible = false
            root.aboutToClose()
            return
        }
        
        if (isAnimating) {
            stopAnimation()
        }
        
        root.aboutToClose()
        hideAnimation.start()
    }
    
    // 停止动画
    function stopAnimation() {
        showAnimation.stop()
        hideAnimation.stop()
        isAnimating = false
        animationStopped()
    }
    
    // 切换显示
    function toggle() {
        if (root.visible) {
            hideAnimated()
        } else {
            showAnimated()
        }
    }
    
    MouseArea {
        anchors.fill: parent
        onClicked: {
            root.hideAnimated()
        }
    }
    
    Keys.onEscapePressed: {
        root.hideAnimated()
    }
}

